﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;

namespace ProxyConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (var item in args)
            {
                Console.Write(item + "  ");
            }
            Console.WriteLine();
            if (args[0] == "clear")
            {
                IESetting.ResetIEProxy();
                Console.WriteLine("reset:");
            }
            else
            {
                IESetting.SetIEProxy(args[0]);
                Console.WriteLine("setproxy:" + args[0]);
            }
        }
    }


    public struct INTERNET_PROXY_INFO
    {
        public int dwAccessType;
        public IntPtr proxy;
        public IntPtr proxyBypass;
    }

    public static class IESetting
    {
        [DllImport(@"wininet", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "InternetSetOption", CallingConvention = CallingConvention.StdCall)]
        public static extern bool InternetSetOption
        (
        IntPtr hInternet,
        int dmOption,
        IntPtr lpBuffer,
        int dwBufferLength
        );

        private const int INTERNET_OPTION_REFRESH = 0x000025;
        private const int INTERNET_OPTION_SETTINGS_CHANGED = 0x000027;
        private static void Reflush()
        {
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
        }

        public static void SetIEProxy(string proxy)
        {
            //打开注册表
            RegistryKey regKey = Registry.CurrentUser;
            string SubKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";

            RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);

            //更改健值，设置代理，
            {
                optionKey.SetValue("ProxyEnable", 1);
                optionKey.SetValue("ProxyServer", proxy);
                Console.WriteLine(Regedit.Instance().GetRegistData(SubKeyPath, "ProxyEnable"));
            }

            //激活代理设置
            Reflush();
            Console.WriteLine(Regedit.Instance().GetRegistData(SubKeyPath, "ProxyEnable"));
        }
        public static void ResetIEProxy()
        {

            //打开注册表
            RegistryKey regKey = Registry.CurrentUser;
            string SubKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";

            RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);

            {
                optionKey.SetValue("ProxyServer", "");
                optionKey.SetValue("ProxyEnable", 0);
                optionKey.Close();
                Console.WriteLine(Regedit.Instance().GetRegistData(SubKeyPath, "ProxyEnable"));
            }

            regKey.Close();
            //激活代理设置
            Reflush();
            Console.WriteLine(Regedit.Instance().GetRegistData(SubKeyPath, "ProxyEnable"));

        }

    }
    public static class IESettings2
    {
        [DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);

        public static void SetIEProxy(string proxy)
        {
            RefreshIESettings(proxy, "", "");
        }
        public static void ResetIEProxy()
        {
            RefreshIESettings("", "", "");
        }
        private static void RefreshIESettings(string strProxy, string proxyUsername, string proxyPassword)
        {

            const int INTERNET_OPTION_PROXY = 38;
            const int INTERNET_OPEN_TYPE_PROXY = 3;
            const int INTERNET_OPTION_PROXY_USERNAME = 43;
            const int INTERNET_OPTION_PROXY_PASSWORD = 44;

            IntPtr username = Marshal.StringToHGlobalAnsi(proxyUsername);
            IntPtr password = Marshal.StringToHGlobalAnsi(proxyPassword);
            INTERNET_PROXY_INFO struct_IPI;
            struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY;

            struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy);
            struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local");

            IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI));
            Marshal.StructureToPtr(struct_IPI, intptrStruct, true);
            bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI));

            Marshal.GetNativeVariantForObject(proxyUsername, username);
            Marshal.GetNativeVariantForObject(proxyPassword, password);
            bool resultF = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY_USERNAME, username, proxyUsername.Length);
            var errorF = Marshal.GetLastWin32Error();

            //-- Set Proxy Password
            bool resultG = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY_PASSWORD, password, proxyPassword.Length + 1);
            var errorG = Marshal.GetLastWin32Error();

        }
    }



    class Regedit
    {
        static Regedit instance = null;
        public static Regedit Instance()
        {
            if (instance == null)
                instance = new Regedit();
            return instance;
        }
        private Regedit() { }

        /// <summary>
        /// 读取指定名称的注册表的值
        /// </summary>
        /// <param name="name">注册表值</param>
        /// <returns></returns>
        public string GetRegistData(string sub, string name)
        {
            string registData;
            RegistryKey hkml = Registry.CurrentUser;
            RegistryKey target = hkml.OpenSubKey(sub, true);
            registData = target.GetValue(name).ToString();
            return registData;
        }

        /// <summary>
        /// 注册表中写数据 
        /// </summary>
        /// <param name="name">注册表</param>
        /// <param name="tovalue">值</param>
        public void WTRegedit(string sub, string name, string tovalue)
        {
            RegistryKey hkml = Registry.CurrentUser;
            RegistryKey target = hkml.OpenSubKey(sub, true);
            target.SetValue(name, tovalue);
        }


    }
}
